#include "cross_graph.h"

CrossEdge* create_cro_eg(int in, int out)
{
    CrossEdge* edge = malloc(sizeof(CrossEdge));
    edge->in = in;
    edge->out = out;
    edge->in_next = NULL;
    edge->out_next = NULL;
    return edge;
}

CrossGraph* create_cro_gp(const char* str)
{
    CrossGraph* g = malloc(sizeof(CrossGraph));
    g->vexnum = strlen(str);
    g->vertex = calloc(sizeof(CrossVertex), g->vexnum);
    for (int i = 0; i < g->vexnum; i++)
    {
        g->vertex[i].vex = str[i];
        //g->vertex[i].head_in = NULL;
        //g->vertex[i].head_out = NULL;
    }
    return g;
}

bool add_eg_cro_gp(CrossGraph* graph, char v1, char v2)
{
    if (graph->vexnum < 2)
        return false;
    int t1 = _get_cro_vex(graph, v1), t2 = _get_cro_vex(graph, v2);
    if (-1 == t1 || -1 == t2 || t1 == t2)
        return false;
    CrossEdge* e = create_cro_eg(t1, t2);
    e->out_next = graph->vertex[t1].head_out;
    graph->vertex[t1].head_out = e;
    e->in_next = graph->vertex[t2].head_in;
    graph->vertex[t2].head_in = e;
    return true;
}

size_t vex_in_cro_gp(CrossGraph* graph, char v)
{
    int t = _get_cro_vex(graph, v);
    if (t == -1)
        return 0;
    size_t cnt = 0;
    for (CrossEdge* e = graph->vertex[t].head_in; NULL != e; e = e->in_next, cnt++);
    return cnt;
}

size_t vex_out_cro_gp(CrossGraph* graph, char v)
{
    int t = _get_cro_vex(graph, v);
    if (t == -1)
        return 0;
    size_t cnt = 0;
    for (CrossEdge* e = graph->vertex[t].head_out; NULL != e; e = e->out_next, cnt++);
    return cnt;
}

int _get_cro_vex(CrossGraph* graph, char v)
{
    for (int i = 0; i < graph->vexnum; i++)
    {
        if (graph->vertex[i].vex == v)
            return i;
    }
    return -1;
}

void traversal_cro_gp(CrossGraph* graph)
{
    for (int i = 0; i < graph->vexnum; i++)
    {
        printf("%d %c:", i, graph->vertex[i].vex);
        for (CrossEdge* e = graph->vertex[i].head_out; NULL != e; e = e->out_next)
        {
            printf("%c ", graph->vertex[e->out].vex);
        }
        printf("\n");
    }
}

